package com.bigdata.spark.core.wc

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object WordCount2 {
  def main(args: Array[String]): Unit = {
    // Spark框架 ---- spark 上下文对象 SparkContext()
    // TODO 建立和Spark框架的连接
    // JDBC : Connection
    val sparkConf = new SparkConf().setMaster("local").setAppName("WordCount")
    val sc = new SparkContext(sparkConf)

    // TODO 执行业务操作
    val line: RDD[String] = sc.textFile("datas/1.txt")

    val words: RDD[String] = line.flatMap(_.split(" "))

    val wordToOne: RDD[(String, Int)] = words.map(
      word => (word, 1)

    )


    val wordGroup: RDD[(String, Iterable[(String, Int)])] = wordToOne.groupBy(t => t._1)

    val wordToCount: RDD[(String, Int)] = wordGroup.map {
      case (word, list) => {
        list.reduce(
          (t1,t2) => {
            (t1._1,t1._2+t2._2)
          }
        )
      }
    }

    // 5. 将转换的结果打印到控制台
    val array: Array[(String, Int)] = wordToCount.collect()

    array.foreach(println)

    // TODO 关闭连接
    sc.stop()
  }
}
